package hivi.vn.hivigold.activities;

import hivi.vn.hivigold.R;
import hivi.vn.hivigold.adapters.SelectDishAdapter;
import hivi.vn.hivigold.database.Preferences;
import hivi.vn.hivigold.database.WebService;
import hivi.vn.hivigold.objects.Ct81;
import hivi.vn.hivigold.objects.Ph81;
import hivi.vn.hivigold.objects.Stock;
import hivi.vn.hivigold.utils.Formats;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.os.Bundle;
import android.text.InputType;
import android.view.Display;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class SelectDish extends Activity {
	SelectDishAdapter adapter;
	ArrayList<Ct81> arrCt81;
	ArrayList<Ph81> arrPh81;
	String Stt_rec = "";

	JSONObject[] objNhvt2, objVt;
	Button[] btnNhvt2, btnVt;

	TextView tv_Ban;
	ListView lv_Data;
	TextView tv_Kho;
	TextView tv_Tongtien;
	EditText txt_Tongtien;
	TextView tv_ck;
	EditText txt_ck;

	Button btn_Pay;
	Button btn_Save;
	Button btn_Cancel;
	Button btn_Delete;
	Button btn_Back;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.select_dish);

		tv_Ban = (TextView) findViewById(R.id.tv_ban);
		tv_Kho = (TextView) findViewById(R.id.tv_kho);
		tv_Tongtien = (TextView) findViewById(R.id.tv_tongtien);
		txt_Tongtien = (EditText) findViewById(R.id.txt_tongtien);
		tv_ck = (TextView) findViewById(R.id.tv_ck);
		txt_ck = (EditText) findViewById(R.id.txt_ck);
		lv_Data = (ListView) findViewById(R.id.lv_data);

		btn_Pay = (Button) findViewById(R.id.btn_pay);
		btn_Save = (Button) findViewById(R.id.btn_save);
		btn_Cancel = (Button) findViewById(R.id.btn_cancel);
		btn_Delete = (Button) findViewById(R.id.btn_delete);
		btn_Back = (Button) findViewById(R.id.btn_back);

		tv_Kho.setOnClickListener(onClickListener);
		txt_ck.setOnClickListener(onClickListener);
		btn_Pay.setOnClickListener(onClickListener);
		btn_Save.setOnClickListener(onClickListener);
		btn_Cancel.setOnClickListener(onClickListener);
		btn_Delete.setOnClickListener(onClickListener);
		btn_Back.setOnClickListener(onClickListener);

		lv_Data.setOnItemClickListener(onItemClickListener);
		lv_Data.setOnItemLongClickListener(onItemLongClickListener);

		Load_SelectedData();
	}

	@Override
	public void onWindowFocusChanged(boolean hasFocus) {
		// TODO Auto-generated method stub
		super.onWindowFocusChanged(hasFocus);
		Load_NhomMon();
	}

	OnClickListener onClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			switch (v.getId()) {
			case R.id.tv_kho:
				Intent i = new Intent(getBaseContext(), SelectStock.class);
				startActivityForResult(i, SelectStock.SELECTED_STOCK_KEY);
				break;
			case R.id.txt_ck:
				ckTxtClick();
				break;
			case R.id.btn_pay:
				payButtonClick();
				break;
			case R.id.btn_save:
				saveButtonClick();
				break;
			case R.id.btn_cancel:
				cancelButtonClick();
				break;
			case R.id.btn_delete:
				deleteButtonClick();
				break;
			case R.id.btn_back:
				backButtonClick();
				break;
			}
		}
	};

	OnItemClickListener onItemClickListener = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
			final AlertDialog.Builder alert = new AlertDialog.Builder(SelectDish.this);

			alert.setTitle(R.string.txt_Title_ck);
			final int position = arg2;
			final EditText input = new EditText(SelectDish.this);
			input.setRawInputType(InputType.TYPE_CLASS_NUMBER);
			alert.setView(input);

			alert.setPositiveButton(R.string.txt_Title_ok, new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int whichButton) {
					String value = input.getText().toString();
					Double ck = (double) 0;
					try {
						ck = Double.parseDouble(value);
					} catch (Exception ex) {
						Toast.makeText(SelectDish.this, R.string.txt_Title_novaild, Toast.LENGTH_LONG).show();
						return;
					}
					if (ck > 100 || ck < 0) {
						Toast.makeText(SelectDish.this, R.string.txt_Title_novaild, Toast.LENGTH_LONG).show();
					} else {
						Ct81 g = arrCt81.get(position);
						g.setCk(Double.parseDouble(value));
						g.setTien((g.getNguyen_gia() - (g.getNguyen_gia() * Double.parseDouble(value)) / 100) * g.getSo_luong());
						adapter = new SelectDishAdapter(SelectDish.this, arrCt81);
						lv_Data.setAdapter(adapter);
						SummaryTien();
						dialog.cancel();
					}
				}
			});

			alert.setNegativeButton(R.string.txt_Title_cancel, new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int whichButton) {
					dialog.cancel();
				}
			});

			alert.show();

		}
	};

	OnItemLongClickListener onItemLongClickListener = new OnItemLongClickListener() {

		@Override
		public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
			// TODO Auto-generated method stub
			switch (arg0.getId()) {

			case R.id.lv_data:
				AlertDialog.Builder adb = new AlertDialog.Builder(SelectDish.this);
				adb.setTitle(R.string.txt_Title_deleteconfirm);
				adb.setMessage(R.string.txt_Title_deleteconrequest);
				final int positionToRemove = arg2;
				adb.setNegativeButton(R.string.txt_Title_cancel, null);
				adb.setPositiveButton(R.string.txt_Title_ok, new AlertDialog.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						arrCt81.remove(positionToRemove);
						adapter = new SelectDishAdapter(SelectDish.this, arrCt81);
						lv_Data.setAdapter(adapter);
						SummaryTien();
					}
				});
				adb.show();
			}
			return false;
		}
	};

	protected void Load_SelectedData() {
		if (Preferences.getPreferenceValue(getBaseContext(), Preferences.SELECTEDTABLEID) == null)
			tv_Ban.setText(R.string.selectTable);
		else
			tv_Ban.setText(Preferences.getPreferenceValue(getBaseContext(), Preferences.SELECTEDTABLENAME).toString().toUpperCase());

		if (Preferences.getPreferenceValue(getBaseContext(), Preferences.STOCKID) == null || Preferences.getPreferenceValue(getBaseContext(), Preferences.STOCKID).equals("*"))
			tv_Kho.setText(R.string.selectStock);
		else
			tv_Kho.setText(Preferences.getPreferenceValue(getBaseContext(), Preferences.STOCKNAME).toString());

		if (Preferences.getPreferenceValue(getBaseContext(), Preferences.SELECTEDTABLESTATUS).equals("0")) {
			if (Preferences.getPreferenceValue(getBaseContext(), Preferences.SELECTEDTABLESTTREC) != null) {
				Stt_rec = Preferences.getPreferenceValue(getBaseContext(), Preferences.SELECTEDTABLESTTREC).toString();
				arrPh81 = WebService.getPh81(getBaseContext(), Stt_rec);
				arrCt81 = WebService.getCt81(getBaseContext(), Stt_rec);
				adapter = new SelectDishAdapter(this, arrCt81);
				lv_Data.setAdapter(adapter);
				txt_ck.setText(Formats.percent(arrPh81.get(0).getCk_tong()));
			}
		} else {
			if (Stt_rec.equals(""))
				Stt_rec = Get_Stt_rec("HDA");
			arrPh81 = WebService.getPh81(getBaseContext(), Stt_rec);
			arrCt81 = WebService.getCt81(getBaseContext(), Stt_rec);
			adapter = new SelectDishAdapter(this, arrCt81);
			lv_Data.setAdapter(adapter);
			txt_ck.setText("0");
		}
		SummaryTien();
	}

	private void Load_NhomMon() {
		String resultNhvv = WebService.getData(this, "dmnhvt2", "Status='1'", "Nhvt2ID,Nhvt2Name");
		try {
			JSONArray json = new JSONArray(resultNhvv);
			btnNhvt2 = new Button[json.length()];
			objNhvt2 = new JSONObject[json.length()];
			LinearLayout lright = (LinearLayout) findViewById(R.id.ll_nhommon);
			LayoutParams param = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 1.0f);
			param.setMargins(5, 5, 5, 5);
			for (int i = 0; i < json.length(); i++) {
				objNhvt2[i] = json.getJSONObject(i);
				btnNhvt2[i] = new Button(getApplicationContext());
				btnNhvt2[i].setText(objNhvt2[i].getString("Nhvt2Name"));
				btnNhvt2[i].setId(i);
				btnNhvt2[i].setBackgroundColor(Color.parseColor("#4197ee"));
				// btnNhvt2[i].setTextSize(20);
				btnNhvt2[i].setHeight(20);
				btnNhvt2[i].setWidth(120);
				btnNhvt2[i].setLayoutParams(param);
				btnNhvt2[i].setPadding(2, 2, 2, 2);
				lright.addView(btnNhvt2[i]);
				btnNhvt2[i].setOnClickListener(handleOnClick(btnNhvt2[i], this));
			}
			LinearLayout lleft = (LinearLayout) findViewById(R.id.ll_left);
			populateText(lright, btnNhvt2, getBaseContext(), lleft);
			clickNhvt2(btnNhvt2[0], this);
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}

	public View.OnClickListener handleOnClick(final Button button, final Context c) {
		return new View.OnClickListener() {
			public void onClick(View v) {
				clickNhvt2(button, c);
			}
		};
	}

	private void clickNhvt2(Button button, Context c) {
		for (int i = 0; i < btnNhvt2.length; i++) {
			btnNhvt2[i].setBackgroundColor(Color.parseColor("#4197ee"));
		}
		button.setBackgroundColor(Color.parseColor("#ce0100"));
		String condition = "", Nhvt2ID = "";
		try {
			Nhvt2ID = objNhvt2[button.getId()].getString("Nhvt2ID");
			condition = "FK_Nhvt2ID = '" + Nhvt2ID + "'";
		} catch (JSONException e) {
			e.printStackTrace();
		}
		String resultVt = WebService.getData(c, "dmvt", condition, "VtID,VtName");
		try {
			JSONArray json = new JSONArray(resultVt);
			btnVt = new Button[json.length()];
			objVt = new JSONObject[json.length()];
			LinearLayout lright = (LinearLayout) findViewById(R.id.ll_mon);
			LayoutParams param = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 1.0f);
			for (int i = 0; i < json.length(); i++) {
				objVt[i] = json.getJSONObject(i);
				btnVt[i] = new Button(getApplicationContext());
				btnVt[i].setText(objVt[i].getString("VtName"));
				btnVt[i].setId(i);
				btnVt[i].setBackgroundColor(Color.parseColor("#77d42a"));
				// btnVt[i].setTextSize(20);
				btnVt[i].setHeight(20);
				btnVt[i].setWidth(120);
				btnVt[i].setLayoutParams(param);
				btnVt[i].setPadding(2, 2, 2, 2);
				btnVt[i].setOnClickListener(handleOnClickVt(btnVt[i], c));
				btnVt[i].setBackgroundColor(Color.parseColor("#77d42a"));
			}
			LinearLayout lleft = (LinearLayout) findViewById(R.id.ll_left);
			populateText(lright, btnVt, c, lleft);
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}

	public View.OnClickListener handleOnClickVt(final Button button, final Context c) {
		return new View.OnClickListener() {
			public void onClick(View v) {
				try {
					clickVt(button, c);
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
		};
	}

	@SuppressLint("SimpleDateFormat")
	private void clickVt(Button button, Context c) throws JSONException {
		if (Preferences.getPreferenceValue(getBaseContext(), Preferences.STOCKID) == null || Preferences.getPreferenceValue(getBaseContext(), Preferences.STOCKID).equals("*")) {
			Toast.makeText(getBaseContext(), R.string.selectStock, Toast.LENGTH_SHORT).show();
			return;
		}

		String vtID = objVt[button.getId()].getString("VtID");
		for (int i = 0; i < btnVt.length; i++) {
			btnVt[i].setBackgroundColor(Color.parseColor("#77d42a"));
		}
		button.setBackgroundColor(Color.parseColor("#ce0100"));
		Boolean check = false;

		// Mon vua chon da co trong hoa don
		for (int i = 0; i < arrCt81.size(); i++) {
			if (arrCt81.get(i).getFk_VtID().equals(vtID)) {
				check = true;

				double ck = arrCt81.get(i).getCk();
				double soluong = arrCt81.get(i).getSo_luong() + 1;
				double tien = soluong * arrCt81.get(i).getGia() * ((100 - ck) / 100);

				arrCt81.get(i).setSo_luong(soluong);
				arrCt81.get(i).setTien(tien);
			}
		}

		// Mon vua chon chua co trong hoa don
		if (check == false) {
			String resultVt = WebService.getData(c, "dmvt", "VtID = '" + vtID + "'", "*");
			JSONArray json = new JSONArray(resultVt);

			Ct81 ct = new Ct81();

			ct.setStt_rec(Stt_rec);
			ct.setStt_rec0(Get_Stt_rec0(arrCt81.size() + 1));
			ct.setFk_VtID(json.getJSONObject(0).getString("VtID"));
			ct.setVtName(json.getJSONObject(0).getString("VtName"));
			ct.setFk_DvtID(json.getJSONObject(0).getString("FK_DvtID"));
			ct.setFK_KhoID(Preferences.getPreferenceValue(getBaseContext(), Preferences.STOCKID));
			ct.setSo_luong(1.0);
			ct.setNguyen_gia(json.getJSONObject(0).getDouble("Gia_Ban0"));
			ct.setCk(0.0);
			ct.setGia_ck(0.0);
			ct.setTien_cong(0.0);
			ct.setGia(json.getJSONObject(0).getDouble("Gia_Ban0"));
			ct.setTien(json.getJSONObject(0).getDouble("Gia_Ban0"));
			ct.setFK_TkID_dt("5111");
			ct.setFK_TkID_vt("156");
			ct.setFK_TkID_gv("632");
			ct.setS3(Preferences.getPreferenceValue(getBaseContext(), Preferences.USERID));
			ct.setUser_id0(Preferences.getPreferenceValue(getBaseContext(), Preferences.USERID));
			ct.setUser_id2(Preferences.getPreferenceValue(getBaseContext(), Preferences.USERID));

			SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
			Date d = new Date();
			ct.setDatetime0(df.format(d));
			ct.setDatetime2(df.format(d));

			arrCt81.add(ct);
		}

		adapter.swaper(arrCt81);
		SummaryTien();
	}

	private String Get_Stt_rec(String vouchercode) {
		String resultStt = WebService.getData(getBaseContext(), "dmstt", "1=1", "Recnumber");
		try {
			JSONArray json = new JSONArray(resultStt);
			int nOrder = json.getJSONObject(0).getInt("Recnumber") + 1;
			String recID = nOrder + "";
			int i = 9;
			int j = recID.trim().length();
			while (j < i) {
				recID = "0" + recID;
				j = j + 1;
			}
			String resultStt2 = WebService.getData(getBaseContext(), "options", "name = 'm_WrkStation'", "val");
			JSONArray json2 = new JSONArray(resultStt2);
			recID = json2.getJSONObject(0).getString("val") + recID + vouchercode.toUpperCase();
			WebService.executeCommand(getBaseContext(), "UPDATE dmstt SET Recnumber = " + nOrder);
			return recID;
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return "";
		}
	}

	private String Get_Stt_rec0(int stt) {
		if (stt < 10)
			return "00" + stt;
		if (stt >= 10 && stt < 100)
			return "0" + stt;
		return "" + stt;
	}

	private String Get_So_ct(String vouchercode) {

		try {
			String resultSct = WebService.getData2(getBaseContext(), "EXEC fs_HG_GET_SCT '" + vouchercode + "'");
			JSONArray json;
			json = new JSONArray(resultSct);
			WebService.executeCommand(getBaseContext(), "UPDATE dmct SET No = No + 1 WHERE CtID = '" + vouchercode + "'");
			return json.getJSONObject(0).getString("So_ct");
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return "";
		}

	}

	private void Post(String sttRec) {
		String text1 = "EXEC fs_PostHDA2Inventory ";
		text1 = (text1 + "'" + "HDA" + "'");
		text1 = (text1 + ", '" + "ph81" + "'");
		text1 = (text1 + ", '" + "ct81" + "'");
		text1 = (text1 + ", '" + sttRec + "'");
		text1 = (text1 + ", '" + "1" + "'");
		WebService.executeCommand(getBaseContext(), text1);
	}

	private void TaoPhieuXuatKho(String sttRec) {
		String soCtPXA = "";
		String sttRecPXA = "";

		sttRecPXA = Get_Stt_rec("PXA");
		soCtPXA = Get_So_ct("PXA");

		SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
		Date d = new Date();

		WebService.executeCommand(getBaseContext(), "exec fs_InsertPXA_FromHDA '" + sttRec + "','" + sttRecPXA + "','" + soCtPXA + "','" + df.format(d) + "'");

	}

	private void payButtonClick() {
		if (save() == true) {
			WebService.executeCommand(getBaseContext(), "UPDATE ph81 SET Status= '1' WHERE Stt_rec ='" + Stt_rec + "' ");
			Post(Stt_rec);
			TaoPhieuXuatKho(Stt_rec);
			backButtonClick();
			Toast.makeText(getBaseContext(), R.string.pay_successalert, Toast.LENGTH_SHORT).show();
		}
	}

	private void saveButtonClick() {
		if (save() == true)
			Toast.makeText(getBaseContext(), R.string.save_successalert, Toast.LENGTH_SHORT).show();
	}

	private boolean save() {
		try {
			String resultSct = WebService.getData2(getBaseContext(), "SELECT * FROM ph81 WHERE Stt_rec = '" + Stt_rec + "'");
			JSONArray json;
			json = new JSONArray(resultSct);

			if (json.length() > 0) {
				if (arrCt81.size() > 0) {
					String sPh81 = "UPDATE ph81 SET ";
					sPh81 = sPh81 + "FK_khoID = '" + Preferences.getPreferenceValue(getBaseContext(), Preferences.STOCKID) + "', ";
					sPh81 = sPh81 + "T_Sl = " + SummarySoLuong() + ", ";
					sPh81 = sPh81 + "Tien_ck = " + SummaryTienCK() + ", ";
					sPh81 = sPh81 + "Ck_tong = " + txt_ck.getText() + ", ";
					sPh81 = sPh81 + "hs_thue = " + "0" + ", ";
					sPh81 = sPh81 + "Tien_thue = " + "0" + ", ";
					sPh81 = sPh81 + "Tien_hang = " + "0" + ", ";
					sPh81 = sPh81 + "T_Tien = " + SummaryTien() + ", ";
					sPh81 = sPh81 + "user_id2 = '" + Preferences.getPreferenceValue(getBaseContext(), Preferences.USERID) + "', ";
					sPh81 = sPh81 + "s3 = '" + Preferences.getPreferenceValue(getBaseContext(), Preferences.USERID) + "', ";
					SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
					Date d = new Date();
					sPh81 = sPh81 + "datetime2 = '" + df.format(d) + "', ";
					sPh81 = sPh81 + "Tien_kd = " + "0" + ", ";
					sPh81 = sPh81 + "Tien_tl = " + "0" + " ";

					sPh81 = sPh81 + "WHERE Stt_rec = '" + Stt_rec + "'";
					WebService.executeCommand(getBaseContext(), sPh81);

					WebService.executeCommand(getBaseContext(), "DELETE FROM ct81 WHERE Stt_rec = '" + Stt_rec + "' ");
					for (int i = 0; i < arrCt81.size(); i++) {
						String sCt81 = "INSERT INTO ct81 (Stt_rec, Stt_rec0, FK_vtID, FK_dvtID, FK_KhoID, Dien_giai, So_luong, Nguyen_gia, Ck, Gia_ck, Tien_cong, Gia, Tien, FK_TkID_dt, FK_TkID_vt, FK_TkID_gv, s3, user_id0, user_id2, datetime0, datetime2) VALUES ('";
						sCt81 = sCt81 + Stt_rec + "','";
						sCt81 = sCt81 + arrCt81.get(i).getStt_rec0() + "','";
						sCt81 = sCt81 + arrCt81.get(i).getFk_VtID() + "',N'";
						sCt81 = sCt81 + arrCt81.get(i).getFk_DvtID() + "','";
						sCt81 = sCt81 + arrCt81.get(i).getFK_KhoID() + "',N'";
						sCt81 = sCt81 + "" + "',";
						sCt81 = sCt81 + arrCt81.get(i).getSo_luong() + ",";
						sCt81 = sCt81 + arrCt81.get(i).getNguyen_gia() + ",";
						sCt81 = sCt81 + arrCt81.get(i).getCk() + ",";
						sCt81 = sCt81 + arrCt81.get(i).getGia_ck() + ",";
						sCt81 = sCt81 + arrCt81.get(i).getTien_cong() + ",";
						sCt81 = sCt81 + arrCt81.get(i).getGia() + ",";
						sCt81 = sCt81 + arrCt81.get(i).getTien() + ",'";
						sCt81 = sCt81 + arrCt81.get(i).getFK_TkID_dt() + "','";
						sCt81 = sCt81 + arrCt81.get(i).getFK_TkID_vt() + "','";
						sCt81 = sCt81 + arrCt81.get(i).getFK_TkID_gv() + "','";
						sCt81 = sCt81 + arrCt81.get(i).getS3() + "','";
						sCt81 = sCt81 + arrCt81.get(i).getUser_id0() + "','";
						sCt81 = sCt81 + arrCt81.get(i).getUser_id2() + "','";
						sCt81 = sCt81 + arrCt81.get(i).getDatetime0() + "','";
						sCt81 = sCt81 + arrCt81.get(i).getDatetime2() + "')";
						WebService.executeCommand(getBaseContext(), sCt81);
					}
					return true;
				} else {
					Toast.makeText(getBaseContext(), R.string.save_requiredetail, Toast.LENGTH_SHORT).show();
					return false;
				}

			} else {

				if (arrCt81.size() > 0) {
					String sPh81 = "INSERT INTO ph81 (Stt_rec, FK_CtID, Ngay_ct, So_ct, Code, Ong_Ba, Dia_Chi, Dien_Giai, FK_NxID, FK_TkID, FK_doitacID, FK_khoID, FK_bpkdID, s3, FK_VvID, FK_NhomgiaID, FK_TkCKID, FK_TkVATID, FK_VatID, T_Sl, Tien_ck, Ck_tong, hs_thue, Tien_thue, Tien_hang, T_Tien, Status, user_id0, user_id2, datetime0, datetime2, FK_KhlID, Tien_kd, Tien_tl) VALUES('";
					sPh81 = sPh81 + Stt_rec + "','";
					sPh81 = sPh81 + "HDA" + "','";

					SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
					Date d = new Date();

					sPh81 = sPh81 + df.format(d) + "','";
					sPh81 = sPh81 + Get_So_ct("HDA") + "',N'',N'',N'',N'','" + Preferences.getPreferenceValue(getBaseContext(), "HtBan") + "','" + Preferences.getPreferenceValue(getBaseContext(), "TkBan") + "','AKL','";
					sPh81 = sPh81 + Preferences.getPreferenceValue(getBaseContext(), Preferences.STOCKID) + "','";
					sPh81 = sPh81 + Preferences.getPreferenceValue(getBaseContext(), Preferences.USERID) + "','";
					sPh81 = sPh81 + Preferences.getPreferenceValue(getBaseContext(), Preferences.USERID) + "','";
					sPh81 = sPh81 + Preferences.getPreferenceValue(getBaseContext(), Preferences.SELECTEDTABLEID) + "','','" + Preferences.getPreferenceValue(getBaseContext(), "TkCk") + "','133','0',";

					sPh81 = sPh81 + SummarySoLuong() + ",";
					sPh81 = sPh81 + SummaryTienCK() + ",";
					sPh81 = sPh81 + txt_ck.getText() + ",";
					sPh81 = sPh81 + "0" + ",";
					sPh81 = sPh81 + "0" + ",";
					sPh81 = sPh81 + "0" + ",";
					sPh81 = sPh81 + SummaryTien() + ",'";

					sPh81 = sPh81 + "0" + "','";
					sPh81 = sPh81 + Preferences.getPreferenceValue(getBaseContext(), Preferences.USERID) + "','";
					sPh81 = sPh81 + Preferences.getPreferenceValue(getBaseContext(), Preferences.USERID) + "','";
					sPh81 = sPh81 + df.format(d) + "','";
					sPh81 = sPh81 + df.format(d) + "','";
					sPh81 = sPh81 + "AKL" + "',";
					sPh81 = sPh81 + "0" + ",";
					sPh81 = sPh81 + "0" + ")";
					WebService.executeCommand(getBaseContext(), sPh81);

					for (int i = 0; i < arrCt81.size(); i++) {
						String sCt81 = "INSERT INTO ct81 (Stt_rec, Stt_rec0, FK_vtID, FK_dvtID, FK_KhoID, Dien_giai, So_luong, Nguyen_gia, Ck, Gia_ck, Tien_cong, Gia, Tien, FK_TkID_dt, FK_TkID_vt, FK_TkID_gv, s3, user_id0, user_id2, datetime0, datetime2) VALUES ('";
						sCt81 = sCt81 + Stt_rec + "','";
						sCt81 = sCt81 + arrCt81.get(i).getStt_rec0() + "','";
						sCt81 = sCt81 + arrCt81.get(i).getFk_VtID() + "',N'";
						sCt81 = sCt81 + arrCt81.get(i).getFk_DvtID() + "','";
						sCt81 = sCt81 + arrCt81.get(i).getFK_KhoID() + "',N'";
						sCt81 = sCt81 + "" + "',";
						sCt81 = sCt81 + arrCt81.get(i).getSo_luong() + ",";
						sCt81 = sCt81 + arrCt81.get(i).getNguyen_gia() + ",";
						sCt81 = sCt81 + arrCt81.get(i).getCk() + ",";
						sCt81 = sCt81 + arrCt81.get(i).getGia_ck() + ",";
						sCt81 = sCt81 + arrCt81.get(i).getTien_cong() + ",";
						sCt81 = sCt81 + arrCt81.get(i).getGia() + ",";
						sCt81 = sCt81 + arrCt81.get(i).getTien() + ",'";
						sCt81 = sCt81 + arrCt81.get(i).getFK_TkID_dt() + "','";
						sCt81 = sCt81 + arrCt81.get(i).getFK_TkID_vt() + "','";
						sCt81 = sCt81 + arrCt81.get(i).getFK_TkID_vt() + "','";
						sCt81 = sCt81 + arrCt81.get(i).getS3() + "','";
						sCt81 = sCt81 + arrCt81.get(i).getUser_id0() + "','";
						sCt81 = sCt81 + arrCt81.get(i).getUser_id2() + "','";
						sCt81 = sCt81 + arrCt81.get(i).getDatetime0() + "','";
						sCt81 = sCt81 + arrCt81.get(i).getDatetime2() + "')";
						WebService.executeCommand(getBaseContext(), sCt81);
					}
					return true;
				} else {
					Toast.makeText(getBaseContext(), R.string.save_requiredetail, Toast.LENGTH_SHORT).show();
					return false;
				}
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}
	}

	private void cancelButtonClick() {
		Load_SelectedData();
	}

	private void deleteButtonClick() {
		WebService.executeCommand(getBaseContext(), "EXEC [fs_DeleteHDA] '" + this.Stt_rec + "', '1'");
		Toast.makeText(getBaseContext(), R.string.delete_successalert, Toast.LENGTH_SHORT).show();
		backButtonClick();
	}

	private void backButtonClick() {
		Intent i2 = new Intent(getBaseContext(), SelectTable.class);
		startActivity(i2);
	}

	private void ckTxtClick() {
		final AlertDialog.Builder alert = new AlertDialog.Builder(SelectDish.this);

		alert.setTitle(R.string.txt_Title_ck);
		final EditText input = new EditText(SelectDish.this);
		input.setRawInputType(InputType.TYPE_CLASS_NUMBER);
		alert.setView(input);

		alert.setPositiveButton(R.string.txt_Title_ok, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				String value = input.getText().toString();
				Double ck = (double) 0;
				try {
					ck = Double.parseDouble(value);
				} catch (Exception ex) {
					Toast.makeText(SelectDish.this, R.string.txt_Title_novaild, Toast.LENGTH_LONG).show();
					return;
				}
				if (ck > 100 || ck < 0) {
					Toast.makeText(SelectDish.this, R.string.txt_Title_novaild, Toast.LENGTH_LONG).show();
				} else {
					txt_ck.setText(Formats.money(ck));
					SummaryTien();
					dialog.cancel();
				}
			}
		});

		alert.setNegativeButton(R.string.txt_Title_cancel, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				dialog.cancel();
			}
		});

		alert.show();
	}

	public static void onStartIntent(Context c) {
		Intent i = new Intent(c, SelectDish.class);
		i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		c.startActivity(i);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == RESULT_OK) {
			Bundle bundle = data.getExtras();
			switch (requestCode) {

			case SelectStock.SELECTED_STOCK_KEY:
				Stock s = (Stock) bundle.getSerializable(SelectStock.SELECTED_STOCK);
				tv_Kho.setText(s.getStockName());
				tv_Kho.setTag(s);
				Preferences.editPreferenceValue(getBaseContext(), Preferences.STOCKID, s.getStockID());
				Preferences.editPreferenceValue(getBaseContext(), Preferences.STOCKNAME, s.getStockName());
				break;
			}
		}
	}

	@SuppressWarnings({ "deprecation" })
	private void populateText(LinearLayout ll, View[] views, Context mContext, LinearLayout ll1) {
		Display display = getWindowManager().getDefaultDisplay();
		ll.removeAllViews();
		int maxWidth = display.getWidth() - ll1.getMeasuredWidth() - 30;
		LinearLayout.LayoutParams params;
		LinearLayout newLL = new LinearLayout(mContext);
		newLL.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
		newLL.setGravity(Gravity.LEFT);
		newLL.setOrientation(LinearLayout.HORIZONTAL);

		int widthSoFar = 0;

		for (int i = 0; i < views.length; i++) {
			LinearLayout LL = new LinearLayout(mContext);
			LL.setOrientation(LinearLayout.HORIZONTAL);
			LL.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM);
			views[i].measure(0, 0);
			params = new LinearLayout.LayoutParams(views[i].getMeasuredWidth(), LayoutParams.WRAP_CONTENT);
			params.setMargins(5, 5, 5, 5);
			LL.addView(views[i], params);
			LL.measure(0, 0);
			widthSoFar += views[i].getMeasuredWidth();
			if (widthSoFar >= maxWidth) {
				ll.addView(newLL);

				newLL = new LinearLayout(mContext);
				newLL.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
				newLL.setOrientation(LinearLayout.HORIZONTAL);
				newLL.setGravity(Gravity.LEFT);
				params = new LinearLayout.LayoutParams(LL.getMeasuredWidth(), LL.getMeasuredHeight());
				newLL.addView(LL, params);
				widthSoFar = LL.getMeasuredWidth();
			} else {
				newLL.addView(LL);
			}
		}
		ll.addView(newLL);
	}

	private double SummaryTien() {
		double summary = 0.0;
		for (int i = 0; i < arrCt81.size(); i++) {
			Ct81 g = arrCt81.get(i);
			summary += g.getTien();
		}
		double ttien = 0.0, ck = 0.0;
		if (txt_ck.getText().toString().equals(""))
			ck = 0.0;
		else
			ck = Double.parseDouble(txt_ck.getText().toString());
		ttien = summary - (summary * ck) / 100;
		txt_Tongtien.setText(Formats.money(ttien));
		return ttien;
	}

	private double SummarySoLuong() {
		double sl = 0.0;
		for (int i = 0; i < arrCt81.size(); i++) {
			sl += arrCt81.get(i).getSo_luong();
		}
		return sl;
	}

	private double SummaryTienCK() {
		double tongtien = 0.0;
		for (int i = 0; i < arrCt81.size(); i++) {
			tongtien = tongtien + arrCt81.get(i).getGia() * arrCt81.get(i).getSo_luong();
		}
		return tongtien - SummaryTien();
	}
}
